import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/login_init_dao.dart';
import 'package:changxindianzishangwu/db/ec_cache.dart';
import 'package:changxindianzishangwu/model/base_model.dart';
import 'package:changxindianzishangwu/model/we_chat_user_info_model.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/web_view.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';

import 'login_update_info_page.dart';

///三方登录=》绑定账号
class LoginBindingAccountPage extends StatefulWidget {
  WeChatUserInfoModel _weChatUserInfoModel;

   LoginBindingAccountPage(this._weChatUserInfoModel, {Key key}) : super(key: key);

  @override
  _LoginBindingAccountPageState createState() =>
      _LoginBindingAccountPageState();
}

class _LoginBindingAccountPageState extends State<LoginBindingAccountPage> {
  TextEditingController _controller;
  TextEditingController _controllerPwd;

  @override
  void initState() {
    // TODO: implement initState
    _controller = TextEditingController();
    _controllerPwd = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    _controllerPwd.dispose();
    // TODO: implement dispose
    EasyLoading.dismiss();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomInset: false,
      appBar: TopAppBar(context, ""),
      body: SingleChildScrollView(
        child: Container(
          constraints: BoxConstraints(
              maxHeight: MediaQuery.of(context).size.height - 45),
          color: Colors.white,
          padding: EdgeInsets.all(15),
          child: _content(),
        ),
      ),
    );
  }

  Column _content() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("绑定自语号", style: _styleTv(18, AppColor.colorDefaultText)),
        Padding(
          padding: const EdgeInsets.only(top: 10, bottom: 30),
          child: Text(
            "${AppString.bindingAccountHint}",
            style: _styleTv(15, AppColor.colorGrey153),
          ),
        ),
        Text(
          "账号",
          style: _styleTv(15, AppColor.colorText85),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 13, bottom: 11),
          child: TextField(
            scrollPadding: EdgeInsets.zero,
            style: _styleTv(13, AppColor.colorDefaultText),
            controller: _controller,
            onChanged: (text) {
              print(text);
            },
            keyboardType: TextInputType.visiblePassword,
            cursorColor: Colors.greenAccent,
            decoration: InputDecoration(
                isDense: true,
                contentPadding: EdgeInsets.only(top: 0, bottom: 11),
                hintText: "请输入",
                hintStyle: _styleTv(sp(16), AppColor.colorGrey153),
                helperText: "账号长度必须为6-12位，英文+数字组合",
                helperStyle: _styleTv(sp(15), AppColor.colorTheme),
                enabledBorder: UnderlineInputBorder(
                  borderSide:
                      BorderSide(color: AppColor.colorGrey245, width: 1),
                )),
            inputFormatters: [
              ///8-16
              WhitelistingTextInputFormatter(
                  RegExp("[a-zA-Z]|[0-9]")), //只能输入汉字或者字母或数字
              LengthLimitingTextInputFormatter(16), //最大长度
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 20),
          child: Text(
            "密码",
            style: _styleTv(15, AppColor.colorText85),
          ),
        ),

        ///数字+字母 8-16
        Padding(
          padding: const EdgeInsets.only(top: 10, bottom: 11),
          child: TextField(
              obscureText: true,
              scrollPadding: EdgeInsets.zero,
              controller: _controllerPwd,
              onChanged: (text) {
                print(text);
              },
              style: _styleTv(13, AppColor.colorDefaultText),
              keyboardType: TextInputType.visiblePassword,
              cursorColor: Colors.greenAccent,
              decoration: InputDecoration(
                  isDense: true,
                  contentPadding: EdgeInsets.zero,
                  border: InputBorder.none,
                  hintText: "请输入",
                  hintStyle: _styleTv(13, AppColor.colorGrey153),
                  helperText: "密码长度必须为8-16位，英文+数字组合",
                  helperStyle: _styleTv(sp(13), AppColor.colorTheme),
                  enabledBorder: UnderlineInputBorder(
                    borderSide:
                        BorderSide(color: AppColor.colorGrey245, width: 1),
                  )),
              inputFormatters: [
                ///8-16
                WhitelistingTextInputFormatter(
                    RegExp("[a-zA-Z]|[0-9]")), //只能输入汉字或者字母或数字
                LengthLimitingTextInputFormatter(16), //最大长度
              ]),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 40),
          child: UniversalView().longBtn("绑定", () {
            print('${_controllerPwd.text}');
            String account=_controller.text.trim();
            String pwd=_controllerPwd.text.trim();
            // if (_controllerPwd.text=="123456") {
            //   _registerUser();
            //   return;
            // }
            if (account.isEmpty) {
              toast("请输入账号");
              return;
            }
            if (pwd.isEmpty) {
              toast("请输入密码");
              return;
            }
            if (!isAccount(account)) {
              toast("账号长度必须为6-12位，英文+数字组合");
              return;
            }
            if (!isPwd(pwd)) {
              toast("密码长度必须为8-12位，英文+数字组合");
              return;
            }
            _bindingUser(account,pwd);
          }),
        ),
        // Expanded(
        //   child: SizedBox(),
        //   flex: 1,
        // ),

        Center(
          child: Text(
            AppString.bindingAccountHint2,
            style: _styleTv(13, AppColor.colorGrey153),
          ),
        )
      ],
    );
  }

  _textUrl(String title, url) {
    return TextSpan(
        text: title,
        style: TextStyle(color: AppColor.colorTheme, fontSize: sp(12)),
        recognizer: new TapGestureRecognizer()
          ..onTap = () {
            Get.to(WebViewExample(
              url: url,
            ));
          });
  }

  TextStyle _styleTv(double size, color) {
    return TextStyle(fontSize: sp(size), color: color);
  }


  void _bindingUser(account, code) async {
    EasyLoading.show();

    var _userinfoModel =
    await LoginInitDao.loginBindingPhone(widget._weChatUserInfoModel, account, code,bindingType: 2);
    if (_userinfoModel is BaseModel) {
      _hideLoading();
      toast("绑定错误：${_userinfoModel.resultMsg}");
      return;
    }
    _loginIm(_userinfoModel);
  }

  _loginIm(_userinfoModel) {
    TencentImSDKPlugin.v2TIMManager
        .login(
      userID: _userinfoModel.data.userId,
      userSig: _userinfoModel.data.userSig,
    )
        .then((res) async {
      _hideLoading();

      if (res.code == 0) {
        getData();
        final XgFlutterPlugin tpush = new XgFlutterPlugin();
        tpush.setAccount(getUserId(), AccountType.UNKNOWN);
        return _userinfoModel.data.isFirstIn == 1
            ? Get.offAllNamed(
          "/homePage",
          arguments: getAppLoginToken(),
        )
            : Get.offAll(LoginUpdateInfoPage(
          weChatUserInfoModel: widget._weChatUserInfoModel, isQr: true,));
      }else{
        toast("IM登录失败 ：${res.desc}");
      }
    });
  }

  getData() async {
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [EcCache.getInstance().get('userId')]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
    }
  }

  void _hideLoading() {
    EasyLoading.dismiss();
  }

  static bool isAccount(String input) {
    RegExp mobile = new RegExp(r"(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$");
    return mobile.hasMatch(input);
  }

  static bool isPwd(String input) {
    RegExp mobile = new RegExp(r"(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$");
    return mobile.hasMatch(input);
  }
}
